var IP = "http://127.0.0.1";
var jQuery;
layui.use(['layer'], function() {
	var $ = layui.$,
		layer = layui.layer;
	jQuery = $;
	$(function() {
		//refresh
		$('#refresh').click(function() {
			location.reload();
		})
		/////////////////////////////////////////////
		$.ajaxSetup({
			cache: false,
			type: "post",
			timeout: 8000,
			contentType: "application/json; charset=utf-8",
			dataType: 'json',
			headers: {
				'token': localStorage.getItem("token") == null ? "" : localStorage.getItem("token")
			},
			beforeSend: function(xhr) {
				layer.load();
			},
			error: function(xhr, textStatus, errorThrown) {
				layer.closeAll('loading');
				var msg = "未知错误";
				console.log(xhr)
				if(xhr.status) {
					if(xhr.status == 400) {
						msg = "参数错误"
						if(xhr.responseJSON) {
							if(xhr.responseJSON.msg) {
								msg = xhr.responseJSON.msg;
							} else if(xhr.responseJSON.error_description) {
								msg = xhr.responseJSON.error_description;
							} else if(xhr.responseJSON.message) {
								msg = xhr.responseJSON.message;
							}
						}
					} else if(xhr.status == 401) {
						msg = "请先登录"
						localStorage.removeItem("access_token");
						setTimeout(function() {
							parent.window.location.href = 'login.html'
						}, 2000)
					} else if(xhr.status == 500) {
						msg = "服务器内部错误"
						if(xhr.responseJSON) {
							if(xhr.responseJSON.msg) {
								msg = xhr.responseJSON.msg;
							} else if(xhr.responseJSON.error_description) {
								msg = xhr.responseJSON.error_description;
							} else if(xhr.responseJSON.message) {
								msg = xhr.responseJSON.message;
							}
						}
					} else if(xhr.status == 403) {
						msg = "无权限操作"
					}
				}
				layer.msg(msg, {
					icon: 2,
					time: 2000
				});
			}
		});
	})
});
//获取url后的参数值
function getUrlParam(key) {
	var href = window.location.href;
	var url = href.split("?");
	if(url.length <= 1) {
		return "";
	}
	var params = url[1].split("&");

	for(var i = 0; i < params.length; i++) {
		var param = params[i].split("=");
		if(key == param[0]) {
			return decodeURI(param[1]);
		}
	}
}
//展示类型为type的数据字典的select框
function showDictSelect(id, type, istitle) {
	var html_d;
	if(istitle) {
		html_d = "<option class='layui-select-tips' value=''>请选择</option>";
	}
	jQuery.each(getDictionary(type), function(idx, obj) {
		html_d += "<option value='" + obj.k + "'>" + obj.v + "</option>";
	});
	jQuery('#' + id).html(html_d);
}

function showCheckbox(id, type) {
	var html_r = "";
	jQuery.each(getDictionary(type), function(idx, obj) {
		html_r += "<input type='checkbox' value='" + obj.id + "' data-id='" + obj.k + "' title='" + obj.v + "' lay-skin='primary'>";
	});
	jQuery('#' + id).html(html_r);
}

function showRolesCheckbox(id) {
	var html_r = "";
	jQuery.each(getRoles(), function(idx, obj) {
		html_r += "<input type='checkbox' data-id='" + obj.id + "' title='" + obj.name + "' lay-skin='primary'>"
	});
	jQuery('#' + id).html(html_r);
}

function showDictRadio(id, type) {
	var html_d = "";
	jQuery.each(getDictionary(type), function(idx, obj) {
		html_d += "<input type='radio' name='sex' value='" + obj.k + "' title='" + obj.v + "'>";
	});
	jQuery('#' + id).html(html_d);
}
//获取全部角色数据
function getRoles() {
	var v = sessionStorage["roles"];
	if(v == null || v == "" || v == undefined) {
		jQuery.ajax({
			url: IP + '/api/admin/role',
			type: 'GET',
			async: false,
			success: function(result, status, xhr) {
				layer.closeAll('loading');
				sessionStorage["roles"] = JSON.stringify(result.data);
			}
		});
	}
	return JSON.parse(sessionStorage["roles"]);
}

//获取类型为type字典数据
function getDictionary(type) {
	var v = sessionStorage[type];
	if(v == null || v == "" || v == undefined) {
		jQuery.ajax({
			url: IP + '/api/admin/dictionary',
			type: 'GET',
			async: false,
			data: {
				type: type
			},
			success: function(result, status, xhr) {
				layer.closeAll('loading');
				sessionStorage[type] = JSON.stringify(result.data);
			}
		});
	}
	return JSON.parse(sessionStorage[type]);
}
//菜单类型，1：菜单是个url，2:是一个按钮(int)
function getMenus(type) {
	var menus;
	jQuery.ajax({
		url: IP + '/api/admin/menus',
		type: 'GET',
		data: {
			type: type
		},
		async: false,
		success: function(result, status, xhr) {
			layer.closeAll('loading');
			menus = result.data;
		}
	});
	return MenuSort(menus);
}
//菜单递归排序后返回
function MenuSort(menuArry) {
	var mymenus = [];
	GetData(0, menuArry);

	function GetData(id, arry) {
		var childArry = GetParentArry(id, arry);
		if(childArry.length > 0) {
			for(var i in childArry) {
				mymenus.push(childArry[i])
				GetData(childArry[i].id, arry);
			}
		}
	}

	function GetParentArry(id, arry) {
		var newArry = new Array();
		for(var i in arry) {
			if(arry[i].parentid == id)
				newArry.push(arry[i]);
		}
		return newArry;
	}
	return mymenus;
}
//刷新
function refresh_token() {
	var flag = true;
	jQuery.ajax({
		url: IP + '/api/admin/sysUser/refresh',
		type: 'POST',
		async: false,
		contentType: "application/x-www-form-urlencoded",
		success: function(result, status, xhr) {
			layer.closeAll('loading');
			flag = false;
		}
	});
	return flag;
}
//判断是否有后缀名
function checkHouZui(fileName) {
	var d = /\.[^\.]+$/.exec(fileName);
	if(d) {
		return true;
	}
	return false;
}
//大小转换
function bytesToSize(bytes) {
	if(bytes === 0) return '0 B';
	var k = 1024,
		sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
		i = Math.floor(Math.log(bytes) / Math.log(k));

	return(bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}